package kt_test.ui.fragment

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.healthapp.R
import kt_test.room.entity.OxygenSampleEntity
import kt_test.viewmodel.OxygenSampleViewModel
import org.json.JSONArray
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet

class OxygenDataViewerFragment : Fragment() {

    private lateinit var inputUserId: EditText
    private lateinit var btnQuery: Button
    private lateinit var btnStartTime: Button
    private lateinit var btnEndTime: Button
    private lateinit var tvSelectedTime: TextView
    private lateinit var recyclerView: RecyclerView
    private lateinit var btnExportJson: Button
    private lateinit var btnExportCsv: Button
    private lateinit var btnOpenChart: Button
    private lateinit var lineChart: LineChart

    private lateinit var adapter: OxygenSampleAdapter

    private var startTime: String? = null
    private var endTime: String? = null

    private val viewModel: OxygenSampleViewModel by viewModels()

    private var currentSamples: List<OxygenSampleEntity> = emptyList()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.fragment_oxygen_data_viewer, container, false)

        inputUserId = view.findViewById(R.id.et_user_id)
        btnQuery = view.findViewById(R.id.btn_query)
        btnStartTime = view.findViewById(R.id.btn_start_time)
        btnEndTime = view.findViewById(R.id.btn_end_time)
        tvSelectedTime = view.findViewById(R.id.tv_selected_time)
        recyclerView = view.findViewById(R.id.rv_samples)
        btnExportJson = view.findViewById(R.id.btn_export_json)
        btnExportCsv = view.findViewById(R.id.btn_export_csv)
        btnOpenChart = view.findViewById(R.id.btn_open_chart)
        lineChart = view.findViewById(R.id.line_chart)

        adapter = OxygenSampleAdapter()
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = adapter

        btnStartTime.setOnClickListener {
            showDateTimePicker { selected ->
                startTime = selected
                updateSelectedTime()
            }
        }

        btnEndTime.setOnClickListener {
            showDateTimePicker { selected ->
                endTime = selected
                updateSelectedTime()
            }
        }

        btnQuery.setOnClickListener {
            val userId = inputUserId.text.toString().ifBlank { null }
            viewModel.querySamples(userId, startTime, endTime)
            Log.d("OxygenQuery", "点击查询按钮，userId=$userId, start=$startTime, end=$endTime")
        }

        btnExportJson.setOnClickListener {
            exportSamplesToJson()
        }

        btnExportCsv.setOnClickListener {
            exportSamplesToCsv()
        }

        btnOpenChart.setOnClickListener {
            if (currentSamples.isEmpty()) {
                Toast.makeText(requireContext(), "暂无数据绘图", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            drawLineChart(currentSamples)
            lineChart.visibility = View.VISIBLE
            Toast.makeText(requireContext(), "已绘制血氧趋势图", Toast.LENGTH_SHORT).show()
        }

        viewModel.samples.observe(viewLifecycleOwner, Observer { list ->
            currentSamples = list
            adapter.updateData(list)
            Log.d("OxygenQuery", "观察到新数据 samples.size = ${list.size}")
        })

        viewModel.loadAllSamples()
        return view
    }

    private fun updateSelectedTime() {
        tvSelectedTime.text = "开始：${startTime ?: "未选"}，结束：${endTime ?: "未选"}"
    }

    private fun showDateTimePicker(onTimeSelected: (String) -> Unit) {
        val calendar = Calendar.getInstance()
        DatePickerDialog(requireContext(), { _, year, month, day ->
            TimePickerDialog(requireContext(), { _, hour, minute ->
                val timeStr = String.format("%04d-%02d-%02d %02d:%02d:00", year, month + 1, day, hour, minute)
                onTimeSelected(timeStr)
            }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true).show()
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show()
    }

    private fun exportSamplesToJson() {
        if (currentSamples.isEmpty()) {
            Toast.makeText(requireContext(), "暂无数据可导出", Toast.LENGTH_SHORT).show()
            return
        }
        try {
            val jsonArray = JSONArray()
            for (sample in currentSamples) {
                val obj = org.json.JSONObject()
                obj.put("time", sample.time)
                obj.put("spo2", sample.spo2)
                jsonArray.put(obj)
            }
            val outputDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            val file = File(outputDir, "oxygen_data_${System.currentTimeMillis()}.json")
            file.writeText(jsonArray.toString(2))
            Toast.makeText(requireContext(), "JSON导出成功：${file.absolutePath}", Toast.LENGTH_LONG).show()
            Log.d("Export", "导出 JSON 文件到：${file.absolutePath}")
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "导出失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun exportSamplesToCsv() {
        if (currentSamples.isEmpty()) {
            Toast.makeText(requireContext(), "暂无数据可导出", Toast.LENGTH_SHORT).show()
            return
        }
        try {
            val outputDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            val file = File(outputDir, "oxygen_data_${System.currentTimeMillis()}.csv")
            val writer = FileWriter(file)
            writer.append("time,spo2\n")
            for (sample in currentSamples) {
                writer.append("${sample.time},${sample.spo2}\n")
            }
            writer.flush()
            writer.close()
            Toast.makeText(requireContext(), "CSV导出成功：${file.absolutePath}", Toast.LENGTH_LONG).show()
            Log.d("Export", "导出 CSV 文件到：${file.absolutePath}")
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "导出失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun drawLineChart(samples: List<OxygenSampleEntity>) {
        val entries = samples.mapIndexed { index, sample ->
            Entry(index.toFloat(), sample.spo2.toFloat())
        }

        val dataSet = LineDataSet(entries, "血氧变化趋势")
        dataSet.lineWidth = 2f
        dataSet.circleRadius = 3f
        dataSet.setDrawValues(false)
        dataSet.setDrawCircles(true)

        val lineData = LineData(dataSet)
        lineChart.data = lineData
        lineChart.description.text = "X轴：采样顺序，Y轴：血氧值(%)"
        lineChart.invalidate() // 刷新折线图
    }

    class OxygenSampleAdapter : RecyclerView.Adapter<OxygenSampleAdapter.ViewHolder>() {
        private var data: List<OxygenSampleEntity> = emptyList()

        fun updateData(newData: List<OxygenSampleEntity>) {
            data = newData
            notifyDataSetChanged()
        }

        class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val tvTime: TextView = view.findViewById(R.id.tv_time)
            val tvSpo2: TextView = view.findViewById(R.id.tv_spo2)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_oxygen_sample, parent, false)
            return ViewHolder(view)
        }

        override fun getItemCount() = data.size

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = data[position]
            holder.tvTime.text = item.time
            holder.tvSpo2.text = "血氧值: ${item.spo2} %"
        }
    }
}
